package org.canaan.security.escape;


import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Map;


/**
 特殊字段规避过滤器
 @Author Canaan
 @Date 2017/9/14 */
public class HttpEscapeRequest extends HttpServletRequestWrapper {

    public HttpEscapeRequest(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {
        return escape(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> nativeMap = super.getParameterMap();
        if (nativeMap == null || nativeMap.isEmpty()) {
            return nativeMap;
        }

        for (String[] items : nativeMap.values()) {
            if (ArrayUtils.isEmpty(items)) {
                continue;
            }
            for (int i = 0; i < items.length; i++) {
                items[i] = escape(items[i]);
            }
        }

        return nativeMap;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] nativeStr = super.getParameterValues(name);
        if (ArrayUtils.isEmpty(nativeStr)) {
            return nativeStr;
        }

        Map<String, String[]> nativeMap = getParameterMap();
        return nativeMap.get(name);
    }


    private String escape(String nativeVal) {
        if (StringUtils.isBlank(nativeVal)) {
            return nativeVal;
        }
        return Jsoup.clean(nativeVal, Whitelist.simpleText());
    }

}
